<?php

namespace AppBundle\Services;


class RedisCache
{
    private $container;
    private $redis;
    private $config = [];

    public function __construct($container, $config = [], $environment = 'dev')
    {
        $this->container = $container;
        $this->config = $config;
        $this->redis = null;
    }

    private function getConfig()
    {
        if (!empty($this->config)) {
            return $this->config;
        }
        throw new \RedisException('no redis parameters config');
    }


    private function connect($config = [])
    {
        $redis = new \Redis();
        if ($redis->connect($config['host'], $config['port'], $config['timeout']) == false) {
            throw new \RedisException('redis server was shutdown.');
        }
        if (!empty($config['auth'])) {
            if ($redis->auth($config['auth']) == false) {
                throw new \RedisException('auth error.');
            }
        }
        $redis->select($config['db']);

        return $redis;
    }

    private function getRedis()
    {
        if ($this->redis)
            return $this->redis;
        $this->redis = $this->connect($this->getConfig());
        return $this->redis;
    }

    public function __call($name, $arguments)
    {
        if (method_exists($this->getRedis(), $name)) {
            return call_user_func_array(array($this->redis, $name), $arguments);
        }
        // todo: add exception
        throw new \Exception(self::class . ' method not exists.', 404);
    }
}